package com.generator.code.util;

import com.generator.code.model.ZipModel;
import com.google.common.collect.Lists;
import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.StringWriter;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author guoq.z
 * @date 2021/4/1
 */
public class ZipUtils {
    /**
     * 创建压缩包
     *
     * @param zipFilePath zip文件路径和名称
     * @param zipModels   zipEntry list
     */
    public static void createZipFile(String zipFilePath, List<ZipModel> zipModels) {
        try {
            File zipFile = new File(zipFilePath);

            if (!zipFile.exists()) {
                File parentFile = zipFile.getParentFile();
                if (!parentFile.exists()) {
                    parentFile.mkdirs();
                }
                zipFile.createNewFile();
            }

            ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zipFile));

            for (ZipModel zipModel : zipModels) {
                zipOutputStream.putNextEntry(new ZipEntry(zipModel.getFileName()));
                zipOutputStream.setComment("hello");

                StringWriter writer = new StringWriter();
                writer.append(zipModel.getContent());
                IOUtils.write(writer.toString(), zipOutputStream, "UTF-8");
                IOUtils.closeQuietly(writer);

                zipOutputStream.closeEntry();
            }

            zipOutputStream.close();

        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    public static void main(String[] args) {
        String zipFilePath = "c:" + File.separator + "generator" + File.separator + "generatorCode.zip";

        ZipModel zipModel = new ZipModel();
        zipModel.setFileName("example.java");
        zipModel.setContent("这里是content");

        ZipModel zipModel1 = new ZipModel();
        zipModel1.setFileName("11example.java");
        zipModel1.setContent("11这里是content");

        createZipFile(zipFilePath, Lists.newArrayList(zipModel, zipModel1));
    }
}
